package com.apes.scm.masterdata.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.stock.model.Depot;
import com.apes.scm.masterdata.stock.repository.DepotRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能：仓库信息
 *
 * @author HuJianlin
 * @create 2018-03-14 9:45
 */
@Service("depotService")
public class DepotService extends DomainService {
    @Autowired
    public DepotRepository depotRepository;

    public Depot save(SimpleRequest request) {
        Depot depot = request.getO(Depot.class);
        if (depot.getId() == null) {
            depot.setId(depot.obtainDepotId(depot));
        }
        return depotRepository.saveAndFlush(depot);
    }

    public String delete(SimpleRequest request) throws Exception {
        String id = request.get("id").toString();
        long versions = (int) request.get("version");

        Depot depot = depotRepository.findOne(id);
        if (depot == null) throw new RuntimeException("工作交接单【" + id + "】在系统中不存在。");
        if (depot.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        depotRepository.delete(depot);

        return "删除成功";
    }

    /**
     * 功能：查询所有的仓库信息
     * @param request
     * @return
     */
    public Page<Depot> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        return depotRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<Depot> find(SimpleRequest request) {
        return depotRepository.find(request.get("key"), PageRequest.of(request.get("page"), request.get("size")) );
    }

    public Depot findOne(SimpleRequest request){
        String var = request.get("id");
        return depotRepository.findOne(var);
    }


    // 提供给 app 调用
    public List queryDepotApp(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        int maxNum = jsonObject.getIntValue("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List depots = depotRepository.findDepotApp(date, PageRequest.of(0, maxNum));
        return depots;
    }
}
